package com.md24housecall.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.md24housecall.activity.HomeActivity;
import com.md24housecall.activity.R;
import com.md24housecall.activity.RatingActivity;
import com.md24housecall.dialog.DialogListDoctor;
import com.md24housecall.dialog.DialogTermsAndCondition;
import com.md24housecall.manager.DimenManager;
import com.md24housecall.manager.SkypeManager;
import com.md24housecall.model.Doctor;
import com.md24housecall.model.User;
import com.md24housecall.net.ParsingUtils;
import com.md24housecall.net.UrlBuilder;
import com.md24housecall.util.GlobalConstant;
import com.md24housecall.util.MyLog;
import com.md24housecall.util.Utils;
import com.md24housecall.view.RatioImageView;
import com.md24housecall.view.RatioRelativeLayout;

public final class RequestCallFragment extends HomeFragment {
	private static final String KEY_TAB_POSITION = "TestFragment:Position";
	private SkypeManager skype = SkypeManager.getInstance();
	private Intent intentRating;
	private boolean isCallSkype = false;
	private GlobalConstant constant = GlobalConstant.getInstance();
	private Utils util = Utils.getInstance();
	private AQuery aQuery;
	private RatioImageView btnCallProvider;
	private RatioImageView btnCallScheduler;
	private RatioImageView btnCallMedicalAssitant;
	private RatioImageView btnCallBilling;
	private CheckBox mChkAgreeTos;

	private RatioImageView mImgHeader;
	private RatioRelativeLayout mHeaderContainer;
	private View.OnClickListener callButtonClick;
	private ProgressDialog mProgressDialog;
	private DialogTermsAndCondition mDlgTerms;
	private boolean isChecked = false;
	private Button btnTermsCondition;
	private AlertDialog alertDlg;
	private int retry=0;
	private final int CLICK_DURATION=1500;
	private AlertDialog dlgAgree;
	private  ArrayList<Doctor> listDoctors=new ArrayList<Doctor>();

	public static RequestCallFragment newInstance(int tabPosition) {
		RequestCallFragment fragment = new RequestCallFragment();

		Bundle args = new Bundle();
		args.putInt(KEY_TAB_POSITION, tabPosition);
		fragment.setArguments(args);

		return fragment;
	}

	private int mTabPosition = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getArguments() != null) {
			mTabPosition = getArguments().getInt(KEY_TAB_POSITION, 0);
		}
	}

	private void getListDoctors(final Context context){
		aQuery.ajax(String.format(UrlBuilder.URL_GETLISTDOCTORBYCODE,constant.code), String.class, new AjaxCallback<String>(){
			@Override
			public void callback(String url, String object,AjaxStatus status) {
				// TODO Auto-generated method stub
				MyLog.d(GlobalConstant.TAG, "url: "+url);
				if(object==null){
					MyLog.d(GlobalConstant.TAG, "no response from server");
					if(retry<3){
						retry++;
						getListDoctors(context);
					}else{
						util.checkConnectionStatus(getActivity(), status, getString(R.string.dlg_call_code_get_error));
						if (mProgressDialog != null && mProgressDialog.isShowing())
							mProgressDialog.dismiss();
						retry=0;
					}
					return;
				}
				retry=0;
//				MyLog.d(GlobalConstant.TAG, "json: "+object);
				try{
					JSONArray jsonArray=null;
					if(object.contains("message")){
						JSONObject jsonObj=new JSONObject(object);
//						MyLog.d(GlobalConstant.TAG, "json: "+jsonObj.getString("message"));
						util.showMessage(RequestCallFragment.this.getActivity(), jsonObj.getString("message"));
						return;
					}
					jsonArray=new JSONArray(object);
					int len=0;
					listDoctors.clear();
					MyLog.d("DucNM","json return: "+object);
					if(jsonArray!=null){
						len=jsonArray.length();
						Doctor doctor=null;
						for(int i=0;i<len;i++){
							try {
								doctor = ParsingUtils.parseDoctors(jsonArray.getJSONObject(i));
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if(doctor!=null)
								listDoctors.add(doctor);
						}
						if(len>1){
							Random r = new Random();
							int position = r.nextInt(len-0);
							MyLog.d(GlobalConstant.TAG, "random position: "+position);
							if(position>=len){
								position=0;
							}
							try{
								Doctor randomDoc=new Doctor();
								Doctor doc=listDoctors.get(position);
								randomDoc.setDoctorId(doc.getDoctorId());
								randomDoc.setDoctorName(getString(R.string.any_doctors_title));
								randomDoc.setDoctorPriority(doc.getDoctorPriority());
								randomDoc.setDoctorSkype(doc.getDoctorSkype());
								randomDoc.setDoctorStatus(doc.getDoctorStatus());
								listDoctors.add(randomDoc);
							}catch(Exception e){
								e.printStackTrace();
							}
						}
					}
					if (mProgressDialog != null && mProgressDialog.isShowing())
						mProgressDialog.dismiss();
					if(status.getCode()==200){
						if (listDoctors.size()>0) {
							DialogListDoctor dlg=new DialogListDoctor(context, listDoctors);
							dlg.show();
						}
					}else {
						constant.isValidCode = false;
						util.checkConnectionStatus(getActivity(), status, getString(R.string.dlg_call_code_get_error));
						return;
					}
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
//				callToSkypeName(skypeNum);
			}
				
		});
		
	}
	
	private void callToSkypeName(int skypeNum) {
		if (!constant.isValidCode && skypeNum==1)
			return;
		MyLog.d(GlobalConstant.TAG,"skypeNum: "+skypeNum);
		switch (skypeNum) {
		case 1:
//			skype.callViaSkype(getActivity(), GlobalConstant.skypeProvider);
			getListDoctors(getActivity());
			break;
		case 2:
			skype.callViaSkype(getActivity(), GlobalConstant.skypeScheduler);
			break;
		case 3:
			skype.callViaSkype(getActivity(), GlobalConstant.skypeMedicalassistant);
			break;
		case 4:
			skype.callViaSkype(getActivity(), GlobalConstant.skypeBilling);
			break;
		default:
			skype.callViaSkype(getActivity(), GlobalConstant.skypeProvider);
			break;
		}
	}

	private void checkCode(final int skypeNum) {
		if(skypeNum>1){
			callToSkypeName(skypeNum);
			return;
		}
		String url = UrlBuilder.buildWSAddUser(constant.code);
		MyLog.d(GlobalConstant.TAG,"retry request call fragment: "+retry);
		constant.isValidCode = false;
		if (mProgressDialog != null && !mProgressDialog.isShowing())
			mProgressDialog.show();
		aQuery.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
			@Override
			public void callback(String url, JSONObject object,AjaxStatus status) {
				isCallSkype = false;
				if(object==null){
					MyLog.d(GlobalConstant.TAG, "no response from server");
					if(retry<3){
						retry++;
						checkCode(skypeNum);
					}else{
						util.checkConnectionStatus(getActivity(), status, getString(R.string.dlg_call_code_get_error));
						if (mProgressDialog != null && mProgressDialog.isShowing())
							mProgressDialog.dismiss();
						retry=0;
					}
					return;
				}
				retry=0;
				User user = ParsingUtils.parseUserManager(object);
				MyLog.d(GlobalConstant.TAG, "checkcode: "+object);
				MyLog.d(GlobalConstant.TAG, "user type: "+user.getType());
				MyLog.d(GlobalConstant.TAG, "user.isDisable(): "+user.isDisable());
//				util.savePreferenceInt(constant.KEYUSERTYPE, getActivity(), user.getType());
				if (mProgressDialog != null && mProgressDialog.isShowing())
					mProgressDialog.dismiss();
				if(status.getCode()==200){
					if (user != null) {
						if (user.isUserEmpty()) {
							constant.isValidCode = false;
							util.saveCode(getActivity(), "");
							getActivity().finish();
							startActivity(new Intent(getActivity(),
									HomeActivity.class));
							Toast.makeText(getActivity(),R.string.dlg_call_code_invalid,Toast.LENGTH_LONG).show();
						} else if (user.isDisable()) {
							constant.isValidCode = false;
	//						ExpireCodeActivity.startExpireCodeDialog(getActivity());
							if(alertDlg!=null && !alertDlg.isShowing() && !getActivity().isFinishing())
								alertDlg.show();
						} else {
							constant.isValidCode = true;
							isCallSkype = true;
						}
					}
				}else {
					constant.isValidCode = false;
					util.checkConnectionStatus(getActivity(), status, getString(R.string.dlg_call_code_get_error));
					return;
				}
				callToSkypeName(skypeNum);
				// if (mProgressDialog != null && mProgressDialog.isShowing())
				// mProgressDialog.dismiss();
			}
		});
	}

	private void initialize() {
		mDlgTerms = new DialogTermsAndCondition(getActivity());
		intentRating = new Intent(getActivity(), RatingActivity.class);
		mProgressDialog = new ProgressDialog(getActivity());
		mProgressDialog.setMessage(getResources().getString(
				R.string.str_loading));
		mProgressDialog.setCancelable(true);
		if (aQuery == null)
			aQuery = new AQuery(getActivity());

		btnTermsCondition=(Button)mainView.findViewById(R.id.btnTermsCondition);
		dlgAgree=new AlertDialog.Builder(getActivity()).setMessage(getString(R.string.dlg_agree_tos_check))
				.setNegativeButton(getString(R.string.button_cancel), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		}).create();
		mImgHeader = (RatioImageView)mainView.findViewById(R.id.imgHeader);
		mImgHeader.setRatio(DimenManager.WIDTH_TAB_HEADER_IMG,
				DimenManager.HEIGHT_TAB_HEADER_IMG);
		mHeaderContainer = (RatioRelativeLayout) mainView
				.findViewById(R.id.header_container);
		mHeaderContainer.setRatio(DimenManager.WIDTH_TAB_HEADER_IMG,
				DimenManager.HEIGHT_TAB_HEADER_IMG);
		mHeaderContainer.setTag("1");

		mChkAgreeTos = (CheckBox)mainView.findViewById(R.id.chk_agree_tos);
		isChecked = util.getPreferenceBoolean(constant.KEYAGREECHECKBOX,
				getActivity(), false);
		mChkAgreeTos.setChecked(isChecked);
		if (isChecked){
			mChkAgreeTos.setEnabled(false);
			mChkAgreeTos.setVisibility(View.GONE);
			btnTermsCondition.setVisibility(View.GONE);
		}

		btnCallProvider = (RatioImageView)mainView
				.findViewById(R.id.btn_call_provider);
		btnCallProvider.setRatio(DimenManager.WIDTH_BUTTON_IMG,
				DimenManager.HEIGHT_BUTTON_IMG);
		btnCallProvider.setTag("1");
		btnCallScheduler = (RatioImageView)mainView
				.findViewById(R.id.btn_call_schedule);
		btnCallScheduler.setRatio(DimenManager.WIDTH_BUTTON_IMG,
				DimenManager.HEIGHT_BUTTON_IMG);
		btnCallScheduler.setTag("2");
		btnCallMedicalAssitant = (RatioImageView)mainView
				.findViewById(R.id.btn_call_medical_assitant);
		btnCallMedicalAssitant.setRatio(DimenManager.WIDTH_BUTTON_IMG,
				DimenManager.HEIGHT_BUTTON_IMG);
		btnCallMedicalAssitant.setTag("3");
		btnCallBilling = (RatioImageView)mainView
				.findViewById(R.id.btn_call_billing);
		btnCallBilling.setRatio(DimenManager.WIDTH_BUTTON_IMG,
				DimenManager.HEIGHT_BUTTON_IMG);
		btnCallBilling.setTag("4");
		constant.isValidCode = true;
		// start:call button skype click
		callButtonClick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!mChkAgreeTos.isChecked()) {
//					AgreeTosDialog.startAgreeTosDialog(getActivity());
					if(dlgAgree!=null && !dlgAgree.isShowing())
						dlgAgree.show();
//						getActivity().startActivity(new Intent(getActivity(),AgreeTosDialog.class));
					return;
				}
				int skypeNum = Integer.parseInt(v.getTag().toString());
				endClick=System.currentTimeMillis();
				if(endClick-startClick>=CLICK_DURATION)
				{
					startClick=endClick;
					checkCode(skypeNum);
//					callToSkypeName(skypeNum);
				}
			}

		};
		// end:call button skype click
		AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
		builder.setMessage(getActivity().getResources().getString(R.string.msg_payment_for_call));
		builder.setPositiveButton(getActivity().getResources().getString(R.string.button_ok), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		alertDlg=builder.create();
		loadImage(R.id.imgHeader, constant.bg_ChoosePeople);
		loadImage(R.id.btn_call_provider, constant.btn_ChoosePeople1);
		loadImage(R.id.btn_call_schedule, constant.btn_ChoosePeople2);
		loadImage(R.id.btn_call_medical_assitant, constant.btn_ChoosePeople3);
		loadImage(R.id.btn_call_billing, constant.btn_ChoosePeople4);
	}

	private void addActions() {
//		mHeaderContainer.setOnClickListener(callButtonClick);
		btnCallProvider.setOnClickListener(callButtonClick);
		btnCallScheduler.setOnClickListener(callButtonClick);
		btnCallMedicalAssitant.setOnClickListener(callButtonClick);
		btnCallBilling.setOnClickListener(callButtonClick);
		mHeaderContainer.setOnClickListener(callButtonClick);
		mChkAgreeTos.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				util.savePreferenceBoolean(constant.KEYAGREECHECKBOX,
						getActivity(), isChecked);
				if (isChecked) {
					buttonView.setEnabled(false);
					mChkAgreeTos.setVisibility(View.GONE);
					btnTermsCondition.setVisibility(View.GONE);
					mDlgTerms.show();
				}
			}
		});
		btnTermsCondition.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mDlgTerms.show();
			}
		});
	}

	@Override
	protected View initView(LayoutInflater inflater,ViewGroup container) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.request_fragment, container, false);
	}
	
	@Override
	protected void initLayout() {
		// TODO Auto-generated method stub
		try {
			initialize();
			addActions();
		} catch (Exception e) {
			// TODO: handle exception
			MyLog.d(GlobalConstant.TAG, "exception onCreateView RequestCallFragment: "+ e.getMessage());
		}
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return super.onCreateView(inflater, container, savedInstanceState);
	}

	private void loadImage(int ImageId, String fileName) {
		File f = new File(constant.file, fileName);
		Bitmap bmp = null;
		if (!fileName.equals("") && f.exists()) {
			bmp = util.getBitmapFromFile(f);
			if (bmp != null)
				((RatioImageView) mainView.findViewById(ImageId))
						.setImageBitmap(bmp);
		} else {
			// maybe load image default
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
//		if (isCallSkype && constant.isLoginSkype) {
//			isCallSkype = false;
//			startActivity(intentRating);
//		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_TAB_POSITION, mTabPosition);
	}
}
